package com.cxria.sms.runtime;

import com.cxria.sms.service.UserService;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CommandRunner {

    private Map<String, Object> services = new HashMap<>();

    private Map<String, Map<String, Method>> methods = new HashMap<>();

    private Map<String, Class<?>> serviceTypes = Map.of("user", UserService.class);

    public CommandRunner(){
        serviceTypes.forEach((type, clazz) ->
            ServiceLoader.load(clazz).findFirst().ifPresent(obj -> {
                services.put(type, obj);
                methods.put(type, Stream.of(obj.getClass().getDeclaredMethods()).collect(
                        Collectors.toMap(Method::getName, Function.identity())
                ));
            })
        );
    }

    public void run(String serviceName, String methodName, List<Object> args){
        Object serviceObj = services.get(serviceName);
        Method method = methods.get(serviceName).get(methodName);
        try {
            Object result = method.invoke(serviceObj, args.toArray());
            System.out.println(result);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

}
